package com.syt.cellphone.information.ui.search

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.syt.cellphone.information.base.BaseViewModel
import com.syt.cellphone.information.data.pojo.PhoneBase
import com.syt.cellphone.information.http.RequestHelp
import com.syt.cellphone.information.http.doFailure
import com.syt.cellphone.information.http.doSuccess
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

/**
 * @author       zhulei
 * @data         2021/1/18 10:55
 * @function    搜索vm
 */
class SearchViewModel(application: Application) : BaseViewModel(application) {

    var searchLiveData = MutableLiveData<List<PhoneBase>>()
    var searchPhones = arrayListOf<PhoneBase>()
    var searchKey: String = ""
    var pageNumber: Int = 0
    var refreshTime: Long = 0

    /**
     * 执行搜索
     * @param key
     * @param refresh 刷新||加载
     */
    fun search(key: String, refresh: Boolean = true) {
        if (key.isEmpty()) {
            return
        }
        searchKey = key
        launch {
            RequestHelp.getClassifyPhone(pageNumber, key)
                .onStart {
                    if (refresh) {
                        searchPhones.clear()
                        pageNumber = 0
                    } else {
                        pageNumber++
                    }
                }
                .collectLatest {value ->  
                    value.doSuccess {
                        searchPhones.addAll(it.list)
                        searchLiveData.postValue(searchPhones)
                    }
                    value.doFailure {
                        toast(it)
                    }
                }
        }
    }
}